package show.hkl.remote.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import show.hkl.remote.util.Demo;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 生成管控http请求
 */
public class ProductControlHTTPCore<T> {
    RestTemplate restTemplate = new RestTemplate();

    private T t;


    /**
     * 通用SQL查询接口请求
     */
    public static final String GET_SQL_QUERY_URL = "http://imc.bx.cisdigital.cn/imc/dispatch/adapter/api/customQuery/queryDataBySql?sqlStr=";


    /**
     * 通过
     *
     * @param sqlStr
     * @return
     */
    public List<T> queryDataBySQL(String sqlStr) {
        // 执行请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(GET_SQL_QUERY_URL + sqlStr, String.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            System.out.println("请求失败");
        }


        // 解析外层数据,判断查询是否成功
        String responseBody = responseEntity.getBody();
        Map<String, Object> responseOuterLayer = (Map<String, Object>) JSONObject.parse(responseBody);
        String code = String.valueOf(responseOuterLayer.get("code"));
        String message = String.valueOf(responseOuterLayer.get("message"));
        if (!"0".equals(code)) {
            System.out.println(message);
            return null;
        }


        // 解析内层数据
        JSONArray responseInnerLayer = (JSONArray) responseOuterLayer.get("data");
        List<T> resultList = new ArrayList<>();
        for (Object responseRowData : responseInnerLayer) {
            T result = conversion(responseRowData);
            resultList.add(result);
        }
        return resultList;
    }

    private T conversion(Object responseRowData) {
        if (responseRowData instanceof Map) {
            return (T) responseRowData;
        } else {
            return null;
        }
    }

    public final static class InnerClass extends ProductControlHTTPCore<Demo> {
        public static Class<?> getTClass() {
            Class<?> clazz = (Class<?>) ((ParameterizedType) InnerClass.class.getGenericSuperclass()).getActualTypeArguments()[0];
            return clazz;
        }
    }


    public static void main(String[] args) {
//        ProductControlHTTPCore<Map<String, Object>> core = new ProductControlHTTPCore<>();
//
//        List<Map<String, Object>> list = core.queryDataBySQL("select * from base_material");
//        list.forEach(System.out::println);

        ProductControlHTTPCore.InnerClass x = new ProductControlHTTPCore.InnerClass();
        System.out.println(InnerClass.getTClass());
    }
}
